<template>

  <!-- 筛选区域 -->
  <div class="filter-form">

    <el-row type="flex" justify="space-between" class="tool-bar">
      <div>
        <el-form ref="form" label-width="100px" :inline="true" size="small">
          <el-form-item label="班级名称">
            <el-input v-model="queryData.class_name" placeholder="班级名称" />
          </el-form-item>
          <el-form-item label="归属学科">
            <el-select v-model="queryData.subject_id" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-select v-model="queryData.state" placeholder="请选择">
              <el-option
                v-for="item in states"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              <!-- <el-option label="禁用" value="禁用" />
              <el-option label="启用" value="启用" /> -->
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="onSearchSubmit">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="onSearchReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button style="margin-left: 120px;" type="primary" size="small" plain @click="dialogShow=true">创建班级</el-button>
      </div>
    </el-row>

    <!-- </el-form> -->

    <!-- 表单区域 -->
    <div class="table-box">
      <el-table :data="list" border style="width: 100%;">
        <!-- prop表示这一列展示哪个数据 -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-row :gutter="10">
                <el-col :span="5">
                  <el-form-item label="班级名称">
                    <span>{{ props.row.class_name }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="5" :offset="2">
                  <el-form-item label="归属学科">
                    <span>{{ props.row.subject_name }}</span>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="10">
                <el-col :span="5">
                  <el-form-item label="讲师">
                    <span>
                      <!-- {{ props.row.teacher_info }} -->
                      <el-button v-for="item,index in JSON.parse(props.row.teacher_info)" :key="index" type="primary" plain disabled size="mini">
                        {{ item.username }}
                      </el-button>
                    </span>

                  </el-form-item>
                </el-col>
                <el-col :span="5" :offset="2">
                  <el-form-item label="助教">
                    <span>
                      <!-- {{ props.row.zhujiao_info }} -->
                      <el-button v-for="item,index in JSON.parse(props.row.zhujiao_info)" :key="index" type="primary" plain disabled size="mini" style="background-color: #fdf6ec;color: #e6a23c;padding:10px; ">
                        {{ item.username }}
                      </el-button>
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="10">
                <el-col :span="5">
                  <el-form-item label="班主任">
                    <span>
                      <!-- {{ props.row.manager_info }} -->
                      <el-button v-for="item,index in JSON.parse(props.row.manager_info)" :key="index" type="primary" plain disabled size="mini" style="background-color: #f0f9eb;color: #67c23a;padding:10px; ">
                        {{ item.username }}
                      </el-button>
                    </span>
                  </el-form-item>
                </el-col>
                <el-col :span="5" :offset="2">
                  <el-form-item label="创建人">
                    <span>{{ props.row.username }}</span>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="10">
                <el-col :span="5">
                  <el-form-item label="开始结束日期">
                    <span>{{ props.row.start_time.slice(0,10) }}至{{ props.row.end_time.slice(0,10) }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="5" :offset="2">
                  <el-form-item label="创建日期">
                    <span>{{ props.row.created_at }}</span>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50px" />
        <el-table-column prop="id" label="班级ID" />
        <el-table-column prop="class_name" label="班级名称" width="150" />
        <el-table-column prop="subject_name" label="归属学科" width="150" />
        <el-table-column prop="teacher_info" label="讲师" width="150">
          <template slot-scope="{row}">
            <el-button v-for="item,index in JSON.parse(row.teacher_info)" :key="index" type="primary" plain disabled size="mini">
              {{ item.username }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="zhujiao_info" label="助教" width="150">
          <template slot-scope="{row}">
            <el-button v-for="item,index in JSON.parse(row.zhujiao_info)" :key="index" type="primary" plain disabled size="mini" style="background-color: #fdf6ec;color: #e6a23c;padding:10px; ">
              {{ item.username }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="manager_info" label="班主任" width="150">
          <template slot-scope="{row}">
            <el-button v-for="item,index in JSON.parse(row.manager_info)" :key="index" type="primary" plain disabled size="mini" style="background-color: #f0f9eb;color: #67c23a;padding:10px; ">
              {{ item.username }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="创建人" width="150" />
        <el-table-column prop="state" label="是否显示" width="150">
          <template slot-scope="scope">
            <!-- {{ `${scope.row.is_show ===1 ? '不显示' : '显示'} ` }} -->
            <el-switch
              v-model="scope.row.state"
              :active-value="1"
              :inactive-value="2"
              active-text="是"
              inactive-text="否"
            />
          </template>
        </el-table-column>
        <el-table-column prop="" label="开始结束日期" width="300">
          <!-- {{ start_time }}至{{ end_time }} -->
          <template slot-scope="{row}">
            {{ row.start_time.slice(0,10) }}至{{ row.end_time.slice(0,10) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建日期" width="300" />

        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="{row}">
            <el-button size="small" type="primary" icon="el-icon-edit" circle @click="editRow(row.id)" />
            <el-button slot="reference" size="small" type="danger" icon="el-icon-delete" circle @click="delRow(row.id)" />
          </template>
        </el-table-column>

      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page">
      <el-row type="flex" justify="end">
        <el-pagination
          :current-page.sync="queryData.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryData.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="sizeChange"
          @current-change="currentChange"
        />
      </el-row>
    </div>
    <!-- 绘制弹窗 -->
    <el-dialog
      :title="`${title}分类`"
      :visible.sync="dialogShow"
      width="45%"
      @close="btnCancel"
    >
      <!-- 绘制表单 -->
      <el-form ref="form" :model="formData" :rules="formRules" label-width="100px" size="normal">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="归属学科" prop="subject_name">
              <el-select v-model="formData.subject_id" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级名称" prop="class_name" style="width:300px">
              <el-input v-model="formData.class_name" placeholder="请输入班级名称" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="授课老师">
              <el-select v-model="teacherID" value-key="id" :multiple="true" placeholder="请选择" @change="valuechange1">
                <el-option
                  v-for="item in teacherList"
                  :key="item.user_id"
                  :label="item.username"
                  :value="item.user_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="助教老师">
              <el-select v-model="zhujiaoID" value-key="id" :multiple="true" placeholder="请选择" @change="valuechange2">
                <el-option
                  v-for="item in zhujiaoList"
                  :key="item.user_id"
                  :label="item.username"
                  :value="item.user_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="班主任老师">
              <el-select v-model="banzhurenId" value-key="id" :multiple="true" placeholder="请选择" @change="valuechange3">
                <el-option
                  v-for="item in banzhurenList"
                  :key="item.user_id"
                  :label="item.username"
                  :value="item.user_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开课结课" style="width:300px">
              <!-- <span class="demonstration">默认</span> -->
              <el-date-picker
                v-model="datetime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @chamge="changeTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="排序" style="width:300px">
              <el-input-number v-model="formData.sort" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="班级状态" prop="state">
              <el-switch
                v-model="formData.state"
                :active-value="1"
                :inactive-value="2"
                active-text="是"
                inactive-text="否"
              />

            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" size="small" @click="btnOk">提交</el-button>
          <el-button size="small" @click="dialogShow=false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>

</template>

<script>
import dayjs from 'dayjs'
import { addClass, delClass, editClass, getBanzhurenList, getClass, getClassList, getDisciplineList, getTeacherList, getZhujiaoList } from '@/api/class/class'
export default {
  data() {
    return {
      list: [], // 表单数据
      queryData: {
        // 请求+搜素
        page: 1,
        limit: 10,
        class_name: '',
        subject_id: '',
        state: ''
      },
      dialogShow: false, // 班级信息添加弹框显示隐藏
      // value1: '',
      options: [], // 归属学科数据
      formData: {
        // 弹框数据
        class_name: '',
        teacher_info: '',
        zhujiao_info: '',
        manager_info: '',
        state: 1,
        sort: 1,
        created_at: '',
        creator_id: '',
        start_time: '',
        end_time: '',
        subject_id: '',
        id: 0

        // subject_name: '',
      },
      // 校验
      formRules: {
        // subject_name: [{ required: true, message: '请选择', tirgger: 'blur' }],
        class_name: [{ required: true, message: '请输入班级名称', tirgger: 'blur' }]
      },
      datetime: [], // 添加弹框时间
      states: [
        // 是否启用
        { value: '1',
          label: '显示'
        },
        { value: '2',
          label: '隐藏'
        }
      ],
      total: 0, // 分页
      teacherList: [], // 讲师列表
      zhujiaoList: [], // 助教列表
      banzhurenList: [], // 班主任列表
      role_name: '讲师',
      role_name1: '助教',
      role_name2: '班主任',
      teacherID: [],
      zhujiaoID: [],
      banzhurenId: []

    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改' : '添加'
    }
  },
  async created() {
    await this.initdata()
    await this.discipline()
    await this.teacher()
    await this.zhujiao()
    await this.banzhuren()
  },
  methods: {
    // 获取整个列表
    async initdata() {
      const res = await getClassList(this.queryData)
      console.log(res, '111111')
      this.list = res.list
      this.total = res.total
      this.list.forEach((item) => {
        item.start_time = dayjs(item.start_time).format('YYYY-DD-MM')
        item.end_time = dayjs(item.end_time).format('YYYY-DD-MM')
      })
    },
    // 获取学科数据
    async discipline() {
      const res = await getDisciplineList()
      console.log(res, '2222222')
      this.options = res
    },
    // 获取讲师列表
    async teacher() {
      const res = await getTeacherList(this.role_name)
      console.log(res, '333333')
      this.teacherList = res
    },
    // 获取助教列表
    async zhujiao() {
      const res = await getZhujiaoList(this.role_name1)
      console.log(res)
      this.zhujiaoList = res
    },
    // 获取班主任列表
    async banzhuren() {
      const res = await getBanzhurenList(this.role_name2)
      console.log(res)
      this.banzhurenList = res
    },
    // 分页
    sizeChange(val) {
      // console.log(val)
      this.queryData.limit = val
      this.initdata()
    },
    currentChange(val) {
      // console.log(val)
      this.queryData.page = val
      this.initdata()
    },
    // 搜素
    onSearchSubmit() {
      this.queryData.page - 1
      this.initdata()
    },
    // 重置
    onSearchReset() {
      this.queryData = {
        page: 1,
        limit: 10,
        class_name: '',
        subject_id: '',
        state: ''
      }
      this.initdata()
    },
    // 选中值发生变化渲染列表
    valuechange1(val) {
      console.log(val)
      const newarr = []
      val.forEach((i) => {
        // filter遍历teacherList数组，将符合条件的拿出形成新的数组
        const arr = this.teacherList.filter(item => item.user_id === i)
        newarr.push(...arr)
      })
      this.formData.teacher_info = newarr
    },
    valuechange2(val) {
      const newarr = []
      val.forEach((i) => {
        const arr = this.zhujiaoList.filter(item => item.user_id === i)
        newarr.push(...arr)
      })
      this.formData.zhujiao_info = newarr
    },
    valuechange3(val) {
      const newarr = []
      val.forEach((i) => {
        const arr = this.banzhurenList.filter(item => item.user_id === i)
        newarr.push(...arr)
      })
      this.formData.manager_info = newarr.slice()
    },

    changeTime() {
      this.formData.start_time = dayjs(this.datetime[0]).format('YYYY-MM-DD')
      this.formData.end_time = dayjs(this.datetime[1]).format('YYYY-MM-DD')
    },

    // 提交表单
    async btnOk() {
      this.changeTime()
      // 表单校验
      await this.$refs.form.validate()
      // 根据是否有id判断   修改或添加信息
      this.formData.id ? await editClass(this.formData) : await addClass(this.formData)
      // 提示
      this.$message.success(this.formData.id ? '修改成功' : '添加成功')
      // 关闭弹框
      this.dialogShow = false
      // 重新渲染
      this.initdata()
    },
    // 清除表单
    btnCancel() {
      this.formData = {
        class_name: '',
        teacher_info: '',
        zhujiao_info: '',
        manager_info: '',
        state: 1,
        sort: 1,
        created_at: '',
        creator_id: '',
        start_time: '',
        end_time: '',
        subject_id: '',
        id: 0
      }

      this.datetime = []
      this.teacherID = []
      this.banzhurenId = []
      this.zhujiaoID = []
      this.$refs.form.clearValidate()
    },
    // 修改
    async editRow(id) {
      console.log(id)
      // 打开弹框
      this.dialogShow = true
      // 获取当前行数据
      const res = await getClass(id)

      // 渲染
      this.formData = res
      // this.formData.manager_info = JSON.parse(res.manager_info)
      this.teacherID = JSON.parse(res.teacher_info).filter(item => item.user_id).map(item => item.username)
      console.log(this.teacherID)
      this.banzhurenId = JSON.parse(res.manager_info).filter(item => item.user_id).map(item => item.username)
      console.log(this.banzhurenId)
      this.zhujiaoID = JSON.parse(res.zhujiao_info).filter(item => item.user_id).map(item => item.username)
      console.log(this.zhujiaoID)

      this.formData.id = id
      this.datetime.push(res.start_time, res.end_time)
    },
    // 删除
    async delRow(id) {
      this.$confirm('确认删除, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delClass({ id: [id] })
        this.$message.success('删除成功')
        // 判断是否是第一页，且删除的数据是否为当前页的最后一个
        if (this.queryData.page > 1 && this.list.length === 1) {
          this.queryData.page--
        }
        this.initdata()

        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss" >

.filter-form,
.tool-bar{
  // border: 1px solid #ddd;
  padding: 15px;
  margin-bottom: 10px;
  background-color: #fff;

}

.disabled{
    ::v-deep .el-upload--picture-card{
        display: none;
    }
}
 .el-form-item{
  margin: 0px;

}

</style>
